package com.lykj.lib_base.internal.utils

import android.content.Context
import android.util.Log
import com.bytedance.hume.readapk.HumeSDK
import com.kwai.monitor.payload.TurboHelper
import com.lykj.lib_base.constants.BConstants
import java.io.IOException
import java.util.*
import java.util.zip.ZipEntry
import java.util.zip.ZipFile


/**
 * 原先用于读取渠道
 */
object ChannelUtils {
    private val TAG = "ChannelUtils"

    //渠道获取
    open fun getChannel(context: Context): String? {
        // 从配置文件中 找到文件
        val appinfo = context.applicationInfo
        val sourceDir = appinfo.sourceDir
        var ret = ""
        var zipfile: ZipFile? = null
        try {
            zipfile = ZipFile(sourceDir)
            val entries: Enumeration<*> = zipfile.entries()
            while (entries.hasMoreElements()) {
                val entry = entries.nextElement() as ZipEntry
                val entryName = entry.name
                if (entryName.startsWith("META-INF/gamechannel")) {
                    ret = entryName
                    break
                }
            }
        } catch (e: IOException) {
            e.printStackTrace()
        } finally {
            if (zipfile != null) {
                try {
                    zipfile.close()
                } catch (e: IOException) {
                    e.printStackTrace()
                }
            }
        }
        val split = ret.split("_").toTypedArray()
        return if (split != null && split.size >= 2) {
            split[1]
        } else {
            null
        }
    }

    /**
     * 读取应用包配置信息(分包信息)
     */
    open fun initReadConfig(ctx:Context) {
        val JU_LIANG_Channel: kotlin.String = HumeSDK.getChannel(ctx)
        val KUAI_SHOU_Channel: kotlin.String  = TurboHelper.getChannel(ctx)

        if (JU_LIANG_Channel.isNullOrBlank() || JU_LIANG_Channel == "bytedance_hume") {
            BConstants.AGENT_CODE = getChannel(ctx) ?: "cps001"
        }  else {
            BConstants.AGENT_CODE = JU_LIANG_Channel
        }

        if (!KUAI_SHOU_Channel.isNullOrBlank()) {
            BConstants.AGENT_CODE = KUAI_SHOU_Channel
        }

        Log.e(TAG, "读取到的分包信息:${BConstants.AGENT_CODE}")
    }
}